<template>
	<view>
		<view class="container">
			<view class="navbar" style="height: 270rpx">
				<view class="inner">
					<view class="mes_tab" :style="'padding-top:' + navbar.top + 'px;'">
						<block v-for="(item, index) in mestaboptions" :key="index">
							<view :class="'tab_item ' + (mestabAct == item.value ? 'act_item' : '')"
								@tap="handleChangeTab" :data-act="item.value">
								{{ item.text }}
								<view class="poa_tabline" v-if="mestabAct == item.value"></view>
								<view :class="'poa_red ' + (mestabAct == item.value ? 'poa_redbig' : '')"
									v-if="tabop[item.value] > 0">{{ tabop[item.value] }}</view>
							</view>
						</block>
					</view>
					<view class="inner_mestab" v-if="mestabAct == 0">
						<view class="mes_bom_in">聊天消息</view>
					</view>
				</view>
			</view>

			<!-- 消息 -->
			<view class="tab_panel" v-if="mestabAct == 0" style="padding: 300rpx 20rpx 200rpx">
				<view class="mes_list">
					<block v-if="messageList.length > 0">
						<uni-swipe-action>
							<block v-for="(item, index) in messageList" :key="index">
								<uni-swipe-action-item :right-options="deloptions" :key="item.Fid"
									@click="handleDelete($event, index, item.Fid)">
									<view class="cell" @tap.native="bindChat(item)" :data-index="item">
										<view class="cell_left">
											<view class="por_avatar">
												<view class="img_box">
													<image
														:src="item.head_url != 'null' ? $com.imageOSS(item.head_url) : $com.imageOSS('avatar-default.png')"
														style="height: 100%; width: 100%" mode="widthFix" />
												</view>
												<view class="number"
													:style="'opacity:' + (item.unreadcount > 0 ? 1 : 0) + ';'">
													{{ item.unreadcount }}
												</view>
											</view>
											<view class="user_mesage">
												<view class="msg_name overHinden">
													{{ item.ShopName || item.nickname || '陌生访客' }}
												</view>
												<view class="msg_text overHinden">
													<view v-if="item.MessageType == 0">{{ item.Msg }}</view>
													<image v-if="item.MessageType == 1" :src="item.Msg"
														style="width: 20px; height: 20px" />
													<image v-if="item.MessageType == 2" :src="item.Msg"
														style="width: 20px; height: 20px" />
													<view v-if="item.MessageType == 3"
														style="height: 20px; display: flex; align-items: center">
														<van-icon size="18px" name="/images/yuyin_l.png" />
														<text>{{ item.shichang }}''</text>
													</view>
													<view v-if="item.MessageType == 4">【交换电话】</view>
													<view v-if="item.MessageType == 5">【优惠券】</view>
													<view v-if="item.MessageType == 6" class="overHinden">
														【{{ item.Msg.title }}】</view>
													<view v-if="item.MessageType == 7">【视频】</view>
													<view v-if="item.MessageType == 8" class="overHinden">【咨询商品底价】</view>
												</view>
											</view>
										</view>
										<view class="time_num">
											<text style="color: #999; font-size: 24rpx">{{ item.CreateTime }}</text>
										</view>
									</view>
								</uni-swipe-action-item>
							</block>
						</uni-swipe-action>
					</block>
					<!-- 加载loading -->
					<kj-loading ref="kjLoading" :abnor="messageList.length == 0"></kj-loading>
				</view>
			</view>

			<!-- 服务通知 -->
			<view class="tab_panel" v-if="mestabAct == 1" style="padding: 280rpx 20rpx 200rpx">
				<view class="fw_list">
					<block v-for="(item, index) in fwlist" :key="index">
						<view class="fw_item">
							<view class="fw_date">{{ item.addtime }}</view>
							<view class="fw_img" v-if="item.url">
								<image
									:src="item.url != 'null' ? $com.imageOSS(item.url) + '?x-oss-process=image/resize,w_300' : $com.imageOSS('abc.jpg')"
									style="height: 100%; width: 100%" />
							</view>
							<view :class="'fw_msg ' + (item.url ? 'fw_isimg' : '')">
								<view class="fw_title">{{ item.title }}</view>
								<view class="fw_content">
									<rich-text :nodes="item.content"></rich-text>
								</view>
							</view>
						</view>
					</block>
				</view>

				<!-- 加载loading -->
				<kj-loading ref="kjLoading" :loadmore="loadmore_fw" :abnor="fwlist.length == 0"></kj-loading>

			</view>

			<!-- 系统消息 -->
			<view class="tab_panel" v-if="mestabAct == 2" style="padding: 300rpx 20rpx 200rpx">
				<view class="fw_list">
					<block v-for="(item, index) in xtlist" :key="index">
						<view class="fw_item">
							<view class="fw_date">{{ item.addtime }}</view>
							<view class="fw_img" v-if="item.url">
								<image
									:src="item.url != 'null' ? $com.imageOSS(item.url) + '?x-oss-process=image/resize,w_300' : $com.imageOSS('abc.jpg')"
									style="height: 100%; width: 100%" />
							</view>
							<!-- 系统消息--开通月度试用会员 -->
							<view class="vip_item" v-if="item.title == '开通月度试用会员'" @tap="handleVip">
								<image :src="$com.imageOSS('xuqiu/m17388360700001434.png')"
									style="height: 100%; width: 100%;" />
							</view>
							<view v-else :class="'fw_msg ' + (item.url ? 'fw_isimg' : '')">
								<view class="fw_title">{{ item.title }}</view>
								<view class="fw_content">
									<rich-text :nodes="item.content"></rich-text>
								</view>
							</view>
						</view>
					</block>
				</view>
				<!-- 加载loading -->
				<kj-loading ref="kjLoading" :loadmore="loadmore_xt" :abnor="xtlist.length == 0"></kj-loading>

			</view>
		</view>

		<tab-bar ref="tabbar" :tabInd="3" :number="number" :v_count="v_count"></tab-bar>
	</view>
</template>

<script>
	import {
		getImage,
		getPage,
		getTabbar,
		ChatConfig
	} from '../../utils/config';
	import api from '../../utils/api';
	import {
		http,
		storage,
		promisify,
		$toast,
		$loading,
		$query
	} from '../../utils/utils';
	import wxApi from '../../utils/wxApi';
	import {
		headerInfo
	} from '../../utils/env';

	let app = getApp()
	let {
		height,
		right,
		menuWidth
	} = headerInfo
	let leftStyle = `right: ${menuWidth / 2 / 2 + right}px`
	let tipTopStyle = `top: ${height}px;`
	let topStyle = `top: ${height + 10}px;`
	export default {
		data() {
			return {
				getPage: getPage,
				logged: 0,
				loading: 0,
				userId: 0,
				goodsNavFix: false,
				goodsNavType: 1,
				goodsList: [],
				pageindex: 1,
				pagesize: 0,
				loadmore: true,
				loaddone: false,
				messageList: [],
				socketOpen: false,

				// WebSocket连接状态
				socketMsgQueue: [],

				// WebSocket消息队列
				manualStop: false,

				//  下拉刷新
				triggered: true,

				//  历史记录当前页
				pageNo: 1,

				scrollHeight: '300px',

				deloptions: [{
					text: '删除',
					style: {
						backgroundColor: 'rgb(255,58,49)'
					}
				}],

				navbar: {
					top: ''
				},

				mestaboptions: [{
						text: '消息',
						value: 0
					},
					{
						text: '服务通知',
						value: 1
					},
					{
						text: '系统消息',
						value: 2
					}
				],

				mestabAct: 0,
				fwlist: [],
				tabop: [0, 0, 0],
				fwpage: 1,
				xtpage: 1,
				fwpageCount: 0,
				xtpageCount: 0,
				loadmore_fw: false,
				loadmore_xt: false,
				window: '',
				xtlist: '',
				number: '',
				v_count: '',
				data: '',
				socket:null
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			//获取system信息
			promisify(uni.getSystemInfo)().then((res) => {
				//获取右上角胶囊信息
				// #ifdef MP-WEIXIN
				this.navbar = uni.getMenuButtonBoundingClientRect()
				console.log("--------------", this.navbar)
				// #endif

				//获取右上角胶囊信息
				// #ifdef MP-TOUTIAO
				let navbar = uni.getMenuButtonBoundingClientRect()
				let CustomButton = tt.getCustomButtonBoundingClientRect()
				navbar.customWidth = CustomButton.customNavigation.width - 10
				navbar.marginLeft = CustomButton.customNavigation.marginLeft + 5
				this.navbar = navbar
				// #endif

				// #ifdef APP-PLUS
				this.navbar = menuButton
				// #endif
				this.window = res
			});
			app.globalData
				.getLogin()
				.then((res) => {
					const {
						user
					} = res.data;
					this.userId = user.user_id;
				})
				.catch((res) => {
					this.logged = res;
					this.goLogin();
				});
			//  设置滚动区域的高度
			this.setScrollHeight();
		},
		/**
		 * 页面滚动函数--监听页面滚动事件
		 */
		onPageScroll(e) {},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		async onShow() {
			const res = await app.globalData.getLogin();
			const {
				user
			} = res.data;
			this.userId = user.user_id;
			console.log('mestabAct============', this.mestabAct)
			if (this.userId > 0) {
				let {
					mestabAct
				} = this;
				this.handleGetMsgCount();
				if (mestabAct == 0) {
					this.connectWebSocket();
					console.log('yonghuid', this.userId);
					this.getMsgList();
				} else if (mestabAct == 1) {
					this.handleGetsysalert((res) => {
						this.fwlist = res.list.reverse();
						this.loadmore_fw = false;
					});
				} else if (mestabAct == 2) {
					this.handleGetsysalert((res) => {
						this.xtlist = res.list.reverse();
						this.loadmore_xt = false;
					});
				}
				if (typeof this.getTabBar === 'function' && this.getTabBar()) {
					console.log('get===', this.getTabBar());
					this.myTime = setInterval(function() {
						this.getTabBar().number = app.globalData.unReadMsg;
						this.getTabBar().v_count = app.globalData.v_count;
					}, 5000)
				}
				// this.getunreadmsg()
			}
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {
			console.log('onHide------------');
			// #ifdef MP-WEIXIN
			console.log('onHide------------');
			uni.closeSocket();
			// #endif
			
			// #ifdef MP-TOUTIAO
			this.socket.close()
			// #endif
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			// #ifdef MP-WEIXIN
			console.log('onHide------------');
			uni.closeSocket();
			// #endif
			
			// #ifdef MP-TOUTIAO
			this.socket.close()
			// #endif
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			uni.showLoading({
				title: '加载中...'
			});
			// 下拉的实际操作
			var pageNo = this.pageNo + 1;
			this.pageNo = pageNo;
			if (this.timer) {
				clearTimeout(this.timer);
			}
			this.timer = setTimeout(() => {
				this.triggered = false;
				this.getMsgList();
				uni.stopPullDownRefresh();
				uni.hideLoading();
			}, 2000);
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			let {
				mestabAct
			} = this;
			if (mestabAct == 1) {
				this.onFwFWReachBottom();
			} else if (mestabAct == 2) {
				this.onXtWReachBottom();
			}
		},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {
			if (this.userId > 0) {
				pageshare += '?pid=' + this.userId;
			}
			return {
				title: ``,
				imageUrl: '',
				path: pageshare,
				success: function(res) {
					console.log('分享');
					//$toast(pageshare);
					if (res.errMsg == 'shareAppMessage:ok') {
						//转发成功
						$toast(pageshare);
						console.log('分享成功');
						if (res.hasOwnProperty('shareTickets')) {
							//分享到群
						} else {
							// 分享到个人
						}
					} else {
						//转发失败
						console.log('分享失败');
					}
				}
			};
		},
		methods: {
			/**
			 * 获取code
			 */
			getLoginCode() {
				return new Promise((resolve) => {
					promisify(uni.checkSession)()
						.then(() => {
							resolve(resCode);
						})
						.catch(() => {
							promisify(uni.login)().then((res) => {
								resolve(res.code);
							});
						});
				});
			},

			handleVip() {
				console.log('handleVip=============')
				const {
					userId
				} = this;
				this.getLoginCode().then((res) => {
					http.post(api.default, {
						data: {
							action: 'pay_data',
							type: 'vip',
							id: 1,
							code: res,
							userid: userId
						}
					}).then((res) => {
						const {
							data
						} = res.data;
						if (res.data.code == 0) {
							const {
								sumPrice,
								source,
								orderId
							} = this;
							let result = -1;

							uni.requestPayment({
								timeStamp: data.timeStamp,
								nonceStr: data.nonceStr,
								package: data.package,
								signType: data.signType,
								paySign: data.paySign,
								success(e) {
									result = 1;
								},
								fail(e) {
									result = 0;
								},
								complete() {
									let pages = null;

									//如果来自我的订单或订单详情 && 付款成功
									if (source > 0 && result == 1) {
										pages = getCurrentPages()[getCurrentPages().length - 2];
									}
									wx.redirectTo({
										url: `${getPage.paymentFeedback}?result=${result}&sumTotal=${data.orderAmount}&source=${source}&orderSn=${data.ordersn}`,
										success() {
											if (pages != undefined || pages != null) {
												console.log(orderId);
												pages.paymentUpdate(orderId);
											}
										}
									});
								}
							});
						} else {
							$toast(res.data.errmsg);
						}
					})
				});
			},
			handleChangeTab(e) {
				console.log('eeeeeeee', e);
				let {
					tabop
				} = this;
				let {
					act
				} = e.currentTarget.dataset;
				this.mestabAct = act;
				tabop[act] = 0;
				if (act == 1) {
					this.handleGetsysalert((res) => {
						this.fwlist = res.list.reverse();
						this.loadmore_fw = false;
					});
				} else if (act == 2) {
					this.handleGetsysalert((res) => {
						this.xtlist = res.list.reverse();
						this.loadmore_xt = false;
					});
				}
				this.tabop = tabop;
			},
			/**
			 * 开启
			 */
			onOpen(event) {
				const {
					position,
					name
				} = event.detail;
			},

			toggleSwipe(e, t) {
				const data = e.currentTarget.dataset || e.target.dataset;
				// data(messageId index)
				const {
					messageList
				} = this;
				if (data.messageId !== undefined) {
					messageList[data.index].isOpen = t;
					this.messageList = messageList
				}
			},

			/**
			 * 删除事件
			 */
			handleDelete(e, index, id) {
				const that = this;
				uni.showModal({
					cancelText: '取消',
					confirmText: '确定',
					content: '是否删除？',
					success(res) {
						if (res.confirm) {
							const messageList = that.messageList;
							http.post(api.default, {
								data: {
									action: 'delfriends',
									fid: id,
									userid: that.userId
								}
							}).then((res) => {
								messageList.forEach((item, index) => {
									if (item.Fid == id) {
										messageList.splice(index, 1);
									}
								});
								$toast(`删除成功`, {
									icon: 'success'
								});
								that.messageList = messageList;
							});
						}
					}
				});
			},

			handleNotouch() {
				return false;
			},

			/**
			 * 禁止手动滑动
			 */
			noSwiping() {
				return false;
			},

			/**
			 * 跳转登录
			 */
			goLogin() {
				wxApi.setStartPage();
				wxApi.navigateTo(getPage.login);
			},

			//连接WebSocket服务器

			connectWebSocket: function() {
				var that = this;
				const socket = uni.connectSocket({
					url: ChatConfig.CIM_URI,
					success: function(res) {
						console.log('WebSocket连接成功');
					},
					fail: function(res) {
						console.log('WebSocket连接失败:', res);
					}
				});
				this.socket = socket;
				
				// #ifdef MP-TOUTIAO
				socket.onOpen(function(res) {
					console.log('WebSocket连接已打开');
					that.socketOpen = true
					for (var i = 0; i < that.socketMsgQueue.length; i++) {
						that.sendSocketMessage(that.socketMsgQueue[i]);
					}
					that.socketMsgQueue = []
					that.innerOnConnectFinished();
				})
				socket.onClose(function(res) {
					console.log('离开页面--------');
					console.log('WebSocket连接已关闭:', res);
					that.socketOpen = false
					// that.innerOnConnectionClosed(res);
				})
				socket.onMessage(function(res) {
					console.log('接收到服务器发送的数据:', res.data);
					that.innerOnMessageReceived(res);
					// var messages = that.data.messages
					// messages.push(res.data)
					// that.setData({
					//   messages: messages,
					//   scrollIntoView: 'message-' + messages.length
					// })
				})
				// #endif
				
				// #ifdef MP-WEIXIN
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开');
					that.socketOpen = true;
					for (var i = 0; i < that.socketMsgQueue.length; i++) {
						that.sendSocketMessage(that.socketMsgQueue[i]);
					}
					that.socketMsgQueue = [];
					that.innerOnConnectFinished();
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败:', res);
				});
				uni.onSocketClose(function(res) {
					console.log('WebSocket连接已关闭:', res);
					that.socketOpen = false;
					// that.innerOnConnectionClosed(res);
				});
				uni.onSocketMessage(function(res) {
					console.log('接收到服务器发送的数据:', res.data);
					that.innerOnMessageReceived(res);
					// var messages = that.data.messages
					// messages.push(res.data)
					// that.setData({
					//   messages: messages,
					//   scrollIntoView: 'message-' + messages.length
					// })
				});
				// #endif
			},

			innerOnConnectFinished: function() {
				let account = '';
				if (account === '' || account === undefined) {
					this.onConnectFinished();
				} else {
					this.bindAccount(account);
				}
			},

			onConnectFinished: function() {
				//获取当前登录用户
				app.globalData.getLogin().then((res) => {
					console.log(res);
					this.bind(res.data.user.user_id);
				});
			},

			bind: function(account) {
				storage.set('account', account);
				let deviceId = ''; //storage.get('deviceId');
				if (deviceId === '' || deviceId === undefined) {
					deviceId = this.generateUUID();
					storage.set('deviceId', deviceId);
				}
				let browser = '微信小程序';
				let body = {};
				body.key = ChatConfig.KEY_CLIENT_BIND;
				body.timestamp = new Date().getTime();
				body.data = {};
				body.data.uid = account;
				body.data.channel = ChatConfig.APP_CHANNEL;
				body.data.appVersion = ChatConfig.APP_VERSION;
				body.data.packageName = ChatConfig.APP_PACKAGE;
				body.data.deviceId = deviceId;
				body.data.deviceName = browser;
				console.log(body);
				this.sendRequest(body);
			},

			sendRequest: function(body) {
				let data = {};
				data.type = ChatConfig.SENT_BODY;
				data.content = JSON.stringify(body);
				this.sendSocketMessage(JSON.stringify(data));
			},

			innerOnMessageReceived(e) {
				console.log(e);
				let data = JSON.parse(e.data);
				let type = data.type;
				let body = data.content;
				if (type === ChatConfig.PING) {
					this.pong();
					return;
				}
				if (type === ChatConfig.MESSAGE) {
					let message = JSON.parse(body);
					this.onInterceptMessageReceived(message);
					return;
				}
				if (type === ChatConfig.REPLY_BODY) {
					let reply = JSON.parse(body);
					/*
					 * 判断是否是握手鉴权失败
					 * 终止后续自动重连
					 */
					if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
						this.manualStop = true;
					}
					this.onReplyReceived(reply);
				}
			},

			pong: function() {
				let data = {};
				data.type = ChatConfig.PONG;
				data.content = ChatConfig.PONG_BODY;
				this.sendSocketMessage(JSON.stringify(data));
			},

			onInterceptMessageReceived(message) {
				/*
				 *被强制下线之后，不再继续连接服务端
				 */
				if (message.action === ChatConfig.ACTION_999) {
					this.manualStop = true
				}
				/*
				 *收到消息后，将消息发送给页面
				 */
				this.onMessageReceived(message);
				app.globalData.unReadMsg++;
				this.getTabBar().number = app.globalData.unReadMsg
			},

			onReplyReceived(reply) {
				console.log(reply);
				if (reply.key === ChatConfig.KEY_CLIENT_BIND && reply.code === ChatConfig.CODE_OK) {
					console.log('登录成功');
					// hideProcess();

					// $('#LoginDialog').fadeOut();

					// $('#MessageDialog').fadeIn();
					// $('#MessageDialog').addClass("in");
					// $("#current_account").text($('#account').val());
				}

				/**
				 * 链接鉴权失败
				 */
				if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
					//hideProcess();
					console.log('鉴权失败');
				}
			},

			onMessageReceived(message) {
				console.log('----------------', message);
				var msgList = this.messageList;
				var extra = message.extra ? JSON.parse(message.extra) : {};
				console.log('msgList----nold', msgList);
				let index = msgList.findIndex((item) => item.FriendId == message.sender);
				var resList = [];
				if (index > -1) {
					let spliceList = msgList.splice(index, 1);
					spliceList.forEach((item) => {
						item.unreadcount = item.unreadcount + 1;
						item.Msg = message.content;
						item.MessageType = extra.MessageType;
						item.shichang = extra.shichang;
					});
					resList = [...spliceList, ...msgList];
				} else {
					// 新的用户消息
					var item = {
						Fid: 0,
						unreadcount: 1,
						ShopName: extra.ShopName,
						ToUserID: message.recevier,
						FromUserId: message.sender,
						Msg: message.content,
						ReadStatus: 0,
						OpId: 0,
						MessageType: extra.MessageType,
						timestamp: message.timestamp,
						shichang: extra.shichang,
						CreateTime: '2024-06-26 17:50:51',
						user_name: extra.user_name,
						nickname: extra.user_name,
						head_url: extra.head_url,
						user_id: message.sender
					};
					if (msgList.length > 0) {
						resList = [item, ...msgList];
					} else {
						resList = [item];
					}
				}
				this.messageList = resList;
				console.log('messagelist----------', this.messageList);
			},

			innerOnConnectionClosed: function(e) {
				var that = this;
				if (!that.manualStop) {
					let time = Math.floor(Math.random() * 16 + 15);
					setTimeout(function() {
						console.log('Socket重新连接');
						that.connectWebSocket(); //重新连接
					}, time);
				}
			},

			generateUUID() {
				let d = new Date().getTime();
				let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					let r = (d + Math.random() * 16) % 16 | 0;
					d = Math.floor(d / 16);
					return (c === 'x' ? r : (r & 3) | 8).toString(16);
				});
				return uuid.replace(/-/g, '');
			},

			// 发送WebSocket消息
			sendSocketMessage: function(message) {
				if (this.socketOpen) {
					// #ifdef MP-TOUTIAO
					this.socket.send({
						data: message
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.sendSocketMessage({
						data: message
					});
					// #endif
				} else {
					this.socketMsgQueue.push(message);
				}
			},

			// 获取未读消息
			getunreadmsg() {
				http.post(
					api.default, {
						data: {
							action: 'getunreadmsgcount',
							userid: this.userId
						}
					},
					false
				).then((res) => {
					app.globalData.unReadMsg = res.data.data;
					if (typeof this.getTabBar === 'function' && this.getTabBar()) {
						console.log('get===', this.getTabBar());
						this.getTabBar().number = app.globalData.unReadMsg
					}
				});
			},

			/**
			 * 消息
			 */
			bindChat(e) {
				console.log('e-------------', e)
				if (e) {
					let parm = {
						touserid: e.user_id,
						user_name: e.ShopName || e.nickname || '陌生访客',
						img: e.head_url
					};
					wxApi.navigateTo('/pages/chat/chat', parm);
				}
			},

			// 获取tab红点
			handleGetMsgCount() {
				let params = {
					data: {
						action: 'getmsgcount',
						userid: this.userId
					}
				};
				http.post(api.default, params, false).then((res) => {
					let {
						data
					} = res.data;
					let tabop = [data.msgcount, data.fw_notice, data.sys_notice];
					let unReadMsg = data.msgcount + data.fw_notice + data.sys_notice;
					this.tabop = tabop;
					app.globalData.unReadMsg = unReadMsg;
					if (typeof this.getTabBar === 'function' && this.getTabBar()) {
						console.log('get===', this.getTabBar());
						this.getTabBar().number = app.globalData.unReadMsg;
					}
				});
			},

			// 获取服务通知/系统消息
			handleGetsysalert(cb) {
				let {
					mestabAct
				} = this;
				let params = {
					action: 'getsysalert',
					userid: this.userId
				};
				if (mestabAct == 1) {
					params.type = 1;
					params.pageIndex = 1;
				} else if (mestabAct == 2) {
					params.type = 2;
					params.pageIndex = 1;
				}
				http.post(
					api.default, {
						data: params
					},
					false
				).then((res) => {
					let {
						data
					} = res.data;
					this.fwpageCount = data.pages;
					console.log('data-----------', data);
					if (cb) {
						cb(data);
					}
				});
			},

			// 获取消息列表
			getMsgList: async function() {
				let params = {
					data: {
						action: 'getfriends',
						userid: this.userId
					}
				};
				const res = await http.post(api.default, params, false);
				var list = res.data.data.list;
				list.forEach((item) => {
					if (item.MessageType == 6) {
						item.Msg = JSON.parse(item.Msg) || {};
					}
				});
				let listRes = list.filter((f) => f.IsShow).reverse();
				this.messageList = listRes;
			},

			// 设置滚动区域的高度
			setScrollHeight: function() {
				const client = uni.getSystemInfoSync().windowHeight; // 获取当前窗口的高度
				console.log('设置滚动区域的高度', client);
				this.scrollHeight = client;
			},

			// 服务触底
			onFwFWReachBottom() {
				console.log('服务触底');
				console.log('到底了');
				let {
					fwpage,
					fwpageCount,
					loadmore_fw
				} = this;
				//未请求完且未在加载中
				if (fwpageCount > fwpage && !loadmore_fw) {
					console.log('eeeeeeeeeeeeeeeeeeeeeeeeeeeee');
					fwpage++;
					loadmore_fw = false;

					//显示加载效果
					this.fwpage = fwpage;
					this.loadmore = loadmore;
					uni.showNavigationBarLoading();

					//请求数据
					this.handleGetsysalert((res) => {
						console.log('底部---------getProductsInfo');
						let {
							fwlist
						} = this;
						loadmore_fw = false;
						this.loadmore_fw = loadmore_fw;
						this.fwlist = fwlist.concat(res.list.reverse());
						//隐藏加载效果
						uni.hideNavigationBarLoading();
					});
				}
			},

			// 系统触底
			onXtWReachBottom() {
				console.log('服务触底');
				console.log('到底了');
				let {
					xtpage,
					xtpageCount,
					loadmore_xt
				} = this;
				//未请求完且未在加载中
				if (xtpageCount > xtpage && !loadmore_xt) {
					console.log('eeeeeeeeeeeeeeeeeeeeeeeeeeeee');
					xtpage++;
					loadmore_xt = false;

					//显示加载效果
					this.xtpage = xtpage;
					this.loadmore_xt = loadmore_xt;
					uni.showNavigationBarLoading();

					//请求数据
					this.handleGetsysalert((res) => {
						console.log('底部---------getProductsInfo');
						let {
							xtlist
						} = this;
						this.loadmore_xt = false;
						this.xtlist = xtlist.concat(res.list.reverse());
						//隐藏加载效果
						uni.hideNavigationBarLoading();
					});
				}
			}
		}
	};
</script>
<style lang="scss">
	@import './message.css';
</style>
